/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package org.flower.httprc.control;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import javafx.scene.control.TreeItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author ZhuYanXin
 */
public class JSONTree {
    private static final Logger LOG = LoggerFactory.getLogger(JSONTree.class);

    public static TreeItem<String> createItem(String name, JsonElement json) {
        TreeItem<String> item = new TreeItem<>();
        if (json.isJsonObject()) {
            item.setValue(name);
            JsonObject jo = json.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> set = jo.entrySet();
            set.forEach(entry -> {
                String key = entry.getKey();
                JsonElement value = entry.getValue();
                TreeItem<String> child = createItem(key, value);
                item.getChildren().add(child);
            });
        } else if (json.isJsonArray()) {
            item.setValue(name);
            JsonArray ja = json.getAsJsonArray();
            Stream.iterate(0, i -> i + 1).limit(ja.size()).forEach(i -> {
                TreeItem<String> child = createItem(String.valueOf(i), ja.get(i));
                item.getChildren().add(child);
            });
        } else {
            item.setValue(name + ":" + json);
        }
        return item;
    }
}
